import { useState, useEffect, useRef, useMemo } from 'react';
import { Table, MF } from 'com';
import { Space, Button } from 'antd';
import { GetList, AddMenu, UpdateMenu, DeleteMenu } from 'api/menus';
import { asyncConfirm } from '@/utils/common';
import menuStore from 'store/menu';

export default () => {
    /**
     * 菜单列表
     */
    const [list, setList] = useState([]);
    /**
     * 原始列表
     */
    const [originList, setOriginList] = useState([]);
    /**
     * loading
     */
    const [loading, setLoading] = useState(false);
    /**
     * 是否添加
     */
    const [isAdd, setIsAdd] = useState(false);
    /**
     * 添加MF引用
     */
    const addMF = useRef();
    /**
     * 要修改的菜单信息
     */
    const [menu, setMenu] = useState({});

    /**
     * 表单配置项
     */
    const options = useMemo(() => ({
        name: {
            title: '菜单名称',
            required: true,
            max: 20
        },
        path: {
            title: '路径',
            required: true,
            max: 50
        },
        code: {
            title: '编码',
            required: true,
            max: 30
        },
        relation: {
            title: '关联菜单',
            tag: 'select',
            attrs: { mode: 'multiple' },
            values: originList.filter(c => c.pid > 0).map(c => ({ label: c.name, value: c.code }))
        },
        sort: {
            title: '排序',
            required: true,
            tag: 'number',
            attrs: { min: 1 }
        },
        show: {
            title: '是否显示',
            tag: 'checkbox'
        }
    }), [list]);

    /**
     * 列
     */
    const cols = [
        {
            title: '菜单名称',
            dataIndex: 'name',
            align: 'left'
        },
        {
            title: '路径',
            dataIndex: 'path',
            align: 'left'
        },
        {
            title: '编码',
            dataIndex: 'code',
            align: 'center'
        },
        {
            title: '关联菜单',
            dataIndex: 'relation',
            align: 'center'
        },
        {
            title: '排序',
            dataIndex: 'sort',
            align: 'center'
        },
        {
            title: '是否显示',
            dataIndex: 'show',
            align: 'center',
            render: text => text ? '显示' : '隐藏'
        },
        {
            title: '操作',
            align: 'center',
            width: 230,
            render: (text, row) => <Space>
                {menuStore.auth('addMenu') && row.pid === 0 && <Button type="link" size="small" onClick={() => openAddMF({ ...row })}>添加子菜单</Button>}
                {menuStore.auth('updateMenu') && <Button type="link" size="small" onClick={() => openAddMF({ ...row }, false)}>编辑</Button>}
                {menuStore.auth('deleteMenu') && <Button type="link" size="small" onClick={() => deleteMenu(row)}>删除</Button>}
            </Space>
        },
    ]

    /**
     * 获取菜单列表
     */
    const getList = async () => {
        try {
            setLoading(true);
            const list = await GetList();
            setOriginList([...list]);
            const _list = list.filter(c => c.pid === 0).map(c => {
                const children = list.filter(d => d.pid === c.id);
                return {
                    ...c,
                    children
                }
            });
            setList(_list);
        } catch (error) { }
        setLoading(false);
    };

    menuStore.auth('menuList') && useEffect(() => {
        getList();
    }, []);

    /**
     * 打开添加MF
     * @param {*} menu 
     */
    const openAddMF = (menu, isAdd = true) => {
        undefined !== menu.relation && (menu.relation = menu.relation?.split(','));
        setMenu(menu);
        setIsAdd(isAdd);
        addMF.current.show();
    }

    /**
     * 提交
     * @param {*} values 
     */
    const confirm = async values => {
        try {
            addMF.current.start();
            await (isAdd ? AddMenu : UpdateMenu)({ id: isAdd ? undefined : menu.id, ...values, pid: isAdd ? menu.id || 0 : menu.pid, show: !!values.show, relation: values.relation?.join() });
            getList();
            addMF.current.hide();
        } catch (error) { }
        addMF.current.stop();
    }

    /**
     * 删除菜单
     * @param {*} row 
     */
    const deleteMenu = async row => {
        let res;
        try {
            res = await asyncConfirm(`您确定要删除【${row.name}】吗？`);
            await DeleteMenu(row.id);
            getList();
        } catch (error) { }
        res && res.close();
    }

    return <div>
        <h3>菜单列表</h3>
        <hr />
        {menuStore.auth('addMenu') && <Button type="primary" onClick={() => openAddMF({})}>添加一级菜单</Button>}
        <p></p>
        {menuStore.auth('menuList') && <Table cols={cols} data={list} loading={loading} />}
        {menuStore.auth('addMenu', 'updateMenu') && <MF onFinish={confirm} ref={addMF} options={options} title={isAdd ? '添加菜单' : '修改菜单'} lw={80} values={isAdd ? {} : menu} />}
    </div>
}